//#include "widget_funca_smart_chat.h"
//#include "ui_widget_funca_smart_chat.h"
//#include <QScrollBar>
//#include <QDebug>
//#include <QTimer>
//#include <ollamaapi.h>
 
//Widget_funcA_Smart_chat::Widget_funcA_Smart_chat(QWidget *parent)
//    : QWidget(parent)
//    , ui(new Ui::Widget_funcA_Smart_chat)  // 初始化 ui 指针
//    , m_ollama(new OllamaAPI(this))
//    , m_currentResponse("")
//    , m_isResponding(false)
//{
//    ui->setupUi(this);
//    ui->chatTextEdit->clear(); // 确保初始为空
//    // 聊天框设置为只读，并启用自动换行
//    ui->chatTextEdit->setReadOnly(true);
//    ui->chatTextEdit->setLineWrapMode(QTextEdit::WidgetWidth);
//    ui->chatTextEdit->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    
//    // 初始化"中止"按钮为隐藏状态（仅在请求时显示）
//    ui->abortButton->setVisible(false);
//    //背景颜色
//    ui->chatTextEdit->setStyleSheet("background-color: #F0FFFF;");
//    // ========== 模型列表初始化 ==========
//    ui->modelComboBox->setToolTip("选择AI模型（默认：deepseek-r1:7b）");
//    // 向下拉框添加可用的AI模型
//    ui->modelComboBox->addItems({"deepseek-r1:7b", "llama2", "mistral"});

//    // ========== 信号槽连接 ==========
//    // 按钮点击事件连接
//    connect(ui->sendButton, &QPushButton::clicked, this, &Widget_funcA_Smart_chat::onSendClicked);
//    connect(ui->abortButton, &QPushButton::clicked, this, &Widget_funcA_Smart_chat::onAbortClicked);
    
//    // 输入框回车键事件连接
//    connect(ui->inputLineEdit, &QLineEdit::returnPressed, this, &Widget_funcA_Smart_chat::onSendClicked);
    
//    // Ollama API信号连接
//    connect(m_ollama, &OllamaAPI::responseStream, this, &Widget_funcA_Smart_chat::onResponseStream);  // 流式响应
//    connect(m_ollama, &OllamaAPI::responseFinished, this, &Widget_funcA_Smart_chat::onResponseFinished);  // 响应完成
//    connect(m_ollama, &OllamaAPI::errorOccurred, this, &Widget_funcA_Smart_chat::onErrorOccurred);  // 错误处理

//    ui->abortButton->setStyleSheet("background-color: #ff6b6b; color: white;");
//    // 显示初始消息
//    appendMessage("系统", "Ollama聊天已就绪，请输入您的问题");
//    updateUIState();  // 更新UI状态（禁用/启用相关控件）
    
//}

//// 其他成员函数实现（保持不变）...
//Widget_funcA_Smart_chat::~Widget_funcA_Smart_chat()
//{
//    delete ui;
//}

//// 发送按钮点击事件处理
//void Widget_funcA_Smart_chat::onSendClicked() {
//    QString message = ui->inputLineEdit->text().trimmed();  // 获取并清理输入文本（输入框）
    
//    // 检查输入是否为空或正在响应中
//    if (message.isEmpty() || m_isResponding) return;
    
//    // 显示用户消息并清空输入框
//    appendMessage("用户", message);
//    m_pendingMessage = message; // 保存到成员变量
//    ui->inputLineEdit->clear();
    
//    // 准备接收AI响应
//    m_currentResponse.clear();
//    m_isResponding = true;
//    updateUIState();  // 更新UI状态（禁用发送按钮，显示中止按钮）
    
////    // 显示"正在思考..."提示
////    appendMessage("AI", "正在思考...");
    
//    // 调用Ollama API发送消息
//    m_ollama->sendMessage(ui->modelComboBox->currentText(), message);
//}

//// 处理AI的流式响应
//void Widget_funcA_Smart_chat::onResponseStream(const QString &partialResponse)
//{
//    static QString lastPartial; // 静态变量，用于去重
    
//    // 跳过重复的响应片段
//    if (partialResponse == lastPartial) return;
//    lastPartial = partialResponse;
    
////    // 累积响应内容
////    m_currentResponse += partialResponse;
    
////    // 格式化响应内容（HTML转义，换行处理）
////    QString formattedResponse = m_currentResponse.toHtmlEscaped()
////        .replace("\n", "<br>")  // 换行符转为HTML换行
////        .replace(" ", "&nbsp;"); // 空格转为HTML空格
//    // 定义 AI 回复的字体样式（例如：微软雅黑、14px、蓝色）
//    QString aiStyle =
//        "<span style=\"font-family: 'Microsoft YaHei'; font-size: 9pt; color: #0066cc;\">";
 
//    // 拼接 HTML 字符串
//    QString formattedResponse = aiStyle + partialResponse + "</span>";
 
//    // 追加到 m_currentResponse（如果是流式拼接）
//    m_currentResponse += formattedResponse;
 
//    // 更新 UI（setHtml 会解析 HTML）
//    ui->chatTextEdit->setHtml(m_currentResponse);
//    //QTimer::singleShot(100, this, &MainWindow::ontimeout);  //延时
//    // 确保滚动条保持在最底部（使用定时器确保在UI更新后执行）
//    QTimer::singleShot(0, [this](){
//        ui->chatTextEdit->verticalScrollBar()->setValue(
//            ui->chatTextEdit->verticalScrollBar()->maximum());
//    });
//}
 
//// 处理AI响应完成
//void Widget_funcA_Smart_chat::onResponseFinished() {
//    // 短暂清空（模拟特效）
//    ui->chatTextEdit->clear();
//    // 延时100ms后显示完整对话
//    QTimer::singleShot(100, this, [this]() {
//        QString userMessage = m_pendingMessage; // 保存待发送的消息;
//        if (!userMessage.isEmpty()) appendMessage("用户", userMessage);
//        if (!m_currentResponse.isEmpty()) appendMessage("AI", m_currentResponse);
        
//        m_isResponding = false;
//        m_currentResponse.clear();
//        updateUIState();
//    });
//}
//// 处理错误情况
//void Widget_funcA_Smart_chat::onErrorOccurred(const QString &error) {
//    m_isResponding = false;  // 重置响应状态
//    updateUIState();  // 更新UI状态
    
//    // 回滚"正在思考..."提示
//    QString text = ui->chatTextEdit->toPlainText();
//    text = text.left(text.lastIndexOf("AI: 正在思考..."));
//    ui->chatTextEdit->setPlainText(text);
    
//    // 显示错误消息
//    appendMessage("系统", "错误: " + error);
//}

//// 中止按钮点击事件处理
//void Widget_funcA_Smart_chat::onAbortClicked() {
//    m_ollama->abortCurrentRequest();  // 调用API中止请求
//    m_isResponding = false;  // 重置响应状态
//    updateUIState();  // 更新UI状态
    
////    // 回滚"正在思考..."提示
////    QString text = ui->chatTextEdit->toPlainText();
////    text = text.left(text.lastIndexOf("AI: 正在思考..."));
////    ui->chatTextEdit->setPlainText(text);
    
//    // 显示中止消息
//    appendMessage("系统", "请求已中止");
//}

//// 追加消息到聊天框（通用方法）
//void Widget_funcA_Smart_chat::appendMessage(const QString &sender, const QString &message) {
//    // 使用HTML格式添加消息（加粗发送者）
//    ui->chatTextEdit->append(QString("<b>%1:</b> %2").arg(sender, message));
    
//    // 确保滚动条保持在最底部
//    ui->chatTextEdit->verticalScrollBar()->setValue(
//    ui->chatTextEdit->verticalScrollBar()->maximum());
//}

//// 更新UI控件状态（根据是否正在响应）
//void Widget_funcA_Smart_chat::updateUIState() {
//    ui->sendButton->setEnabled(!m_isResponding);    // 发送按钮
//    ui->abortButton->setVisible(m_isResponding);    // 中止按钮
//    ui->modelComboBox->setEnabled(!m_isResponding); // 模型选择框
//    ui->inputLineEdit->setEnabled(!m_isResponding); // 输入框
//}

////已激活
//void Widget_funcA_Smart_chat::on_modelComboBox_activated(const QString &arg1)
//{
    
//}

#include "widget_funca_smart_chat.h"
#include "ui_widget_funca_smart_chat.h"
#include <QScrollBar>
#include <QDebug>
#include <QTimer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <ollamaapi.h>

Widget_funcA_Smart_chat::Widget_funcA_Smart_chat(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget_funcA_Smart_chat)
    , m_ollama(new OllamaAPI(this))
    , m_currentResponse("")
    , m_isResponding(false)
    , currentReply(nullptr)
{
    ui->setupUi(this);

    // 窗口样式设置
    this->setStyleSheet("background-color: #f0f9ff;");

    // 聊天显示区域配置
    ui->chatTextEdit->setReadOnly(true);
    ui->chatTextEdit->setLineWrapMode(QTextEdit::WidgetWidth);
    ui->chatTextEdit->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    ui->chatTextEdit->setStyleSheet("background-color: #F0FFFF; border: 1px solid #d9ecf2; border-radius: 5px;");

    // 输入框设置
    ui->inputLineEdit->setStyleSheet("background-color: #ffffff; border: 1px solid #c5e2f6; border-radius: 5px; padding: 5px;");
    ui->inputLineEdit->setFont(QFont("楷体", 13));
    ui->inputLineEdit->setPlaceholderText("有什么问题都可以在这里输入 😊");

    // 按钮样式
    ui->sendButton->setFixedSize(80, 30);
    ui->sendButton->setStyleSheet("QPushButton { background-color: #66b3ff; color: white; border-radius: 5px; }"
                                 "QPushButton:hover { background-color: #3399ff; }");
    ui->abortButton->setStyleSheet("background-color: #ff6b6b; color: white; border-radius: 5px;");
    ui->abortButton->setVisible(false);

    // 模型选择框
    ui->modelComboBox->setStyleSheet("QComboBox { border: 1px solid #c5e2f6; border-radius: 5px; padding: 5px; }");
    ui->modelComboBox->setToolTip("选择AI模型");
    ui->modelComboBox->addItems({"deepseek-r1:7b", "llama2", "mistral", "glm-4-flash"});

    // 信号槽连接
    connect(ui->sendButton, &QPushButton::clicked, this, &Widget_funcA_Smart_chat::onSendClicked);
    connect(ui->abortButton, &QPushButton::clicked, this, &Widget_funcA_Smart_chat::onAbortClicked);
    connect(ui->inputLineEdit, &QLineEdit::returnPressed, this, &Widget_funcA_Smart_chat::onSendClicked);
    // 连接 activated(const QString &text) 信号
    connect(ui->modelComboBox, QOverload<const QString &>::of(&QComboBox::activated),
            this, &Widget_funcA_Smart_chat::onModelChanged);
    // Ollama API信号
    connect(m_ollama, &OllamaAPI::responseStream, this, &Widget_funcA_Smart_chat::onResponseStream);
    connect(m_ollama, &OllamaAPI::responseFinished, this, &Widget_funcA_Smart_chat::onResponseFinished);
    connect(m_ollama, &OllamaAPI::errorOccurred, this, &Widget_funcA_Smart_chat::onErrorOccurred);

    // 网络管理器初始化
    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &Widget_funcA_Smart_chat::onReplyFinished);

    appendMessage("系统", "聊天已就绪，请输入您的问题");
    updateUIState();
}

Widget_funcA_Smart_chat::~Widget_funcA_Smart_chat()
{
    onAbortClicked(); // 中止所有请求
    delete ui;
    delete m_ollama;
    delete manager;
}

void Widget_funcA_Smart_chat::onSendClicked()
{
    QString message = ui->inputLineEdit->text().trimmed();
    if (message.isEmpty() || m_isResponding) return;

    // 显示用户消息
    appendMessage("用户", message);
    m_pendingMessage = message;
    ui->inputLineEdit->clear();

    // 准备接收响应
    m_currentResponse.clear();
    m_isResponding = true;
    updateUIState();

    // 根据选择的模型调用不同API
    QString selectedModel = ui->modelComboBox->currentText();
    if (selectedModel == "glm-4-flash") {
        // 调用智谱AI API
        sendToZhipuAI(selectedModel, message);
    } else {
        // 调用Ollama本地模型
        m_ollama->sendMessage(selectedModel, message);
    }
}

void Widget_funcA_Smart_chat::sendToZhipuAI(const QString &model, const QString &message)
{
    QUrl url("https://open.bigmodel.cn/api/paas/v4/chat/completions");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", "dc5cfce794b24ee5b6902adb043f60f8.E9OuLkwJfxnAYimU");

    // 构建请求JSON
    QJsonObject msg;
    msg["role"] = "user";
    msg["content"] = message;

    QJsonArray messages;
    messages.append(msg);

    QJsonObject json;
    json["model"] = model;
    json["messages"] = messages;
    json["max_tokens"] = 65536;
    json["temperature"] = 1.0;

    QJsonDocument doc(json);
    qDebug() << "发送智谱AI请求:" << doc.toJson();

    // 发送请求并保存当前回复对象
    currentReply = manager->post(request, doc.toJson());
}

void Widget_funcA_Smart_chat::onResponseStream(const QString &partialResponse)
{
    static QString lastPartial;
    if (partialResponse == lastPartial) return;
    lastPartial = partialResponse;

    // 格式化AI回复
    QString aiStyle = "<span style=\"font-family: 'Microsoft YaHei'; font-size: 9pt; color: #0066cc;\">";
    QString formattedResponse = aiStyle + partialResponse + "</span>";

    m_currentResponse += formattedResponse;
    ui->chatTextEdit->setHtml(m_currentResponse);

    // 保持滚动到底部
    QTimer::singleShot(0, [this](){
        ui->chatTextEdit->verticalScrollBar()->setValue(
            ui->chatTextEdit->verticalScrollBar()->maximum());
    });
}

void Widget_funcA_Smart_chat::onResponseFinished()
{
    ui->chatTextEdit->clear();
    QTimer::singleShot(100, [this]() {
        if (!m_pendingMessage.isEmpty()) appendMessage("用户", m_pendingMessage);
        if (!m_currentResponse.isEmpty()) appendMessage("AI", m_currentResponse);

        m_isResponding = false;
        m_currentResponse.clear();
        updateUIState();
    });
}

void Widget_funcA_Smart_chat::onReplyFinished(QNetworkReply *reply)
{
    if (reply != currentReply) { // 忽略已中止的请求
        reply->deleteLater();
        return;
    }

    if (reply->error() != QNetworkReply::NoError) {
        if (reply->error() != QNetworkReply::OperationCanceledError) {
            appendMessage("系统", "网络错误: " + reply->errorString());
        }
    } else {
        QByteArray response = reply->readAll();
        QJsonParseError err;
        QJsonDocument doc = QJsonDocument::fromJson(response, &err);

        if (err.error == QJsonParseError::NoError && doc.isObject()) {
            QJsonObject responseObject = doc.object();
            if (responseObject.contains("error")) {
                QString errorMsg = responseObject["error"].toObject()["message"].toString();
                appendMessage("系统", "API错误: " + errorMsg);
            } else if (responseObject.contains("choices") &&
                      responseObject["choices"].isArray() &&
                      !responseObject["choices"].toArray().isEmpty()) {
                QJsonObject choice = responseObject["choices"].toArray().first().toObject();
                QString content = choice["message"].toObject()["content"].toString();
                appendMessage("AI", content);
            } else {
                appendMessage("系统", "响应格式异常");
            }
        } else {
            appendMessage("系统", "JSON解析错误: " + err.errorString());
        }
    }

    m_isResponding = false;
    currentReply->deleteLater();
    currentReply = nullptr;
    updateUIState();
}

void Widget_funcA_Smart_chat::onErrorOccurred(const QString &error)
{
    m_isResponding = false;
    updateUIState();
    appendMessage("系统", "错误: " + error);
}

void Widget_funcA_Smart_chat::onAbortClicked()
{
    // 中止Ollama请求
    m_ollama->abortCurrentRequest();

    // 中止智谱AI请求
    if (currentReply) {
        currentReply->abort();
        currentReply->deleteLater();
        currentReply = nullptr;
    }

    if (m_isResponding) {
        m_isResponding = false;
        appendMessage("系统", "请求已中止");
        updateUIState();
    }
}

void Widget_funcA_Smart_chat::appendMessage(const QString &sender, const QString &message)
{
    QString senderStyle = (sender == "用户") ? "color: #cc0000;" : "color: #0066cc;";
    ui->chatTextEdit->append(QString("<b style=\"%1\">%2:</b> %3")
        .arg(senderStyle, sender, message.toHtmlEscaped()));

    ui->chatTextEdit->verticalScrollBar()->setValue(
        ui->chatTextEdit->verticalScrollBar()->maximum());
}

void Widget_funcA_Smart_chat::updateUIState()
{
    ui->sendButton->setEnabled(!m_isResponding);
    ui->abortButton->setVisible(m_isResponding);
    ui->modelComboBox->setEnabled(!m_isResponding);
    ui->inputLineEdit->setEnabled(!m_isResponding);
}

void Widget_funcA_Smart_chat::onModelChanged(const QString &model)
{
    appendMessage("系统", "已切换模型: " + model);
}

